package validate

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
	"reflect"
)

func Check(ctx *gin.Context, obj interface{}) error {
	//绑定参数
	err := ctx.Bind(obj)
	if err != nil {
		//解析错误信息
		value := reflect.TypeOf(obj)
		if errs, ok := err.(validator.ValidationErrors); ok {
			for _, e := range errs {
				if f, exist := value.Elem().FieldByName(e.Field()); exist {
					if value, ok := f.Tag.Lookup("errmsg"); ok {
						return fmt.Errorf("%s", value)
					} else {
						return fmt.Errorf("%s", e.Value())
					}
				}
			}
		}
	}
	return nil
}
